import socket
import uuid


class NacosConfig:
    def __init__(self, 
                 server_addr="localhost:8848", 
                 namespace="public", 
                 service_name="media-info-process",
                 group_name="DEFAULT_GROUP"):
        """
        初始化Nacos配置
        
        Args:
            server_addr: Nacos服务器地址，格式为"ip:port"
            namespace: Nacos命名空间
            service_name: 服务名称
            group_name: 服务组名
        """
        self.server_addr = server_addr
        self.namespace = namespace
        self.service_name = service_name
        self.group_name = group_name
        
        # 获取本机IP地址
        self.ip = self._get_host_ip()
        # 生成唯一实例ID
        self.instance_id = f"{self.ip}-{str(uuid.uuid4())[:8]}"
        
    def _get_host_ip(self):
        """获取本机IP地址"""
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            ip = s.getsockname()[0]
            s.close()
            return ip
        except Exception:
            # 如果无法获取，返回localhost
            return '127.0.0.1'
    
    def get_client_config(self):
        """获取Nacos客户端配置"""
        return {
            'server_addresses': self.server_addr,
            'namespace': self.namespace
        }
    
    def get_service_instance(self, port=5555, weight=1.0, enabled=True, healthy=True, metadata=None):
        """
        获取服务实例配置
        
        Args:
            port: 服务端口
            weight: 实例权重
            enabled: 是否启用
            healthy: 是否健康
            metadata: 元数据字典
        
        Returns:
            服务实例配置字典
        """
        if metadata is None:
            metadata = {
                'version': '1.0.0',
                'preserved.heart.beat.interval': '5000',  # 心跳间隔，单位毫秒
                'preserved.heart.beat.timeout': '15000',  # 心跳超时，单位毫秒
                'preserved.ip.delete.timeout': '30000',   # IP删除超时，单位毫秒
                'preserved.register.source': 'PYTHON_CLIENT'
            }
        
        return {
            'ip': self.ip,
            'port': port,
            'service_name': self.service_name,
            'group_name': self.group_name,
            'weight': weight,
            'enabled': enabled,
            'healthy': healthy,
            'metadata': metadata,
            'instance_id': self.instance_id
        }